package org.ehe.finance.receivable.mapper;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.ehe.common.mybatis.annotation.DataColumn;
import org.ehe.common.mybatis.annotation.DataPermission;
import org.ehe.common.mybatis.core.mapper.BaseMapperPlus;
import org.ehe.finance.receivable.domain.ErpFinanceReceivable;
import org.ehe.finance.receivable.domain.vo.ErpFinanceReceivableVo;

/**
 * 应收账款Mapper接口
 * @author :zhangnn
 * @className :ErpFinanceReceivableMapper
 * @description: 应收账款数据访问层
 * @date 2025-08-28 10:00:00
 */
@DataPermission({
    @DataColumn(key = "deptName", value = "create_dept"),
    @DataColumn(key = "userName", value = "create_by")
})
public interface ErpFinanceReceivableMapper extends BaseMapperPlus<ErpFinanceReceivable, ErpFinanceReceivableVo> {

    /**
     * 获取客户应收账款汇总
     *
     * @param customerId 客户ID
     * @return 汇总信息
     */
    @Select("""
        SELECT
            c.customer_name,
            COUNT(*) as total_count,
            COALESCE(SUM(r.total_amount), 0) as total_amount,
            COALESCE(SUM(r.paid_amount), 0) as paid_amount,
            COALESCE(SUM(r.unpaid_amount), 0) as unpaid_amount,
            COALESCE(SUM(CASE WHEN r.due_date < CURDATE() AND r.settlement_status IN (1,2) THEN r.unpaid_amount ELSE 0 END), 0) as overdue_amount,
            COUNT(CASE WHEN r.due_date < CURDATE() AND r.settlement_status IN (1,2) THEN 1 END) as overdue_count
        FROM erp_finance_receivable r
        LEFT JOIN erp_finance_customer c ON r.customer_id = c.id
        WHERE r.customer_id = #{customerId}
        AND r.del_flag = '0'
        GROUP BY c.customer_name
        """)
    ErpFinanceReceivableVo selectCustomerReceivableSummary(@Param("customerId") Long customerId);
}
